package jpb.module.rest.member;

import jpb.constant.LogState;
import jpb.constant.Reply;
import jpb.constant.ReturnState;
import jpb.constant.StatusCode;
import jpb.module.daomain.member.Member;
import jpb.module.service.member.MemberService;
import jpb.security.HandleCookie;
import jpb.security.HandleToken;
import jpb.security.ProduceJwt;
import jpb.util.NetworkUtil;
import jpb.util.RespUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * Created by haol on 2017/3/14.
 */
@RestController
@RequestMapping("/api/app/log")
public class MemberLoginController {
        @Autowired
        private MemberService memberService;

        private HandleToken handleToken = new HandleToken();
        private ProduceJwt produceJwt = new ProduceJwt();

        private Logger logger = LoggerFactory.getLogger(MemberLoginController.class);


        /**
         *@api {POST} /api/app/log/login 登录
         * @apiGroup MemberLogin
         * @apiName Login
         * @apiDescription 组织成员登录
         *   @apiParam {String} memberNum 账号(not null)
         *  @apiParam {String} password 密码(not null)
         *  @apiParamExample {json} 请求样例：
         *  POST /api/app/log/login
         *   {
         *       "memberNum": "201430098009"
         *   }
         *  @apiSuccessExample {json} 返回样例:
         *  {
         *      "code":0,"msg":"登录成功"
         *  }
         */
        @RequestMapping(value = "/login", method = RequestMethod.POST)
        public String Login(String memberNum, HttpServletResponse response, HttpServletRequest request) {
                Member member = memberService.getLog(memberNum);
                if (member != null) {

                        long nowMillis = System.currentTimeMillis();
                        Date nowTime = new Date(nowMillis);

                        String subject = handleToken.generalSubject(member);
                        String jwt = produceJwt.produceAppToken(StatusCode.JWT_ID, subject, StatusCode.JWT_APP_TTL, nowTime);
                        HandleCookie.saveCookie(response, StatusCode.COOKIE_JWT_APP, jwt);

                        memberService.updateLoginTime(member.getMemberNum(), nowTime);

                        logger.info("用户[{}]登录成功,IP地址为[{}]", memberNum,NetworkUtil.getIpAddress(request));

                        RespUtil.setACAO(response);
                        if (memberService.getCount(member.getMemberNum()) == 0) {
                                return new Reply(2,ReturnState.NO_MSG).toJson();
                        }
                        return new Reply(0,LogState.LOGIN_SUCCESS).toJson();

                } else {
                        logger.info("用户[{}]登录失败,账号不存在", memberNum);
                        HandleCookie.deleteCookie(response, StatusCode.COOKIE_JWT_APP);
                        return new Reply(1,LogState.LOGIN_FAIL).toJson();
                }
        }

        /**
         *@api {GET} /api/app/log/logout  退出登录
         * @apiGroup MemberLogin
         * @apiName Logout
         *  @apiDescription 组织管理员退出登录
         *  @apiSuccessExample {json} 返回样例:
         *  {
         *      "code":0,"msg":"登出成功"
         *  }
         */
        @RequestMapping(value = "/logout", method = RequestMethod.GET)
        public String accountOut(HttpServletResponse response) {
                HandleCookie.deleteCookie(response, StatusCode.COOKIE_JWT_APP);
                logger.info("用户退出成功");
                return new Reply(0,LogState.LOGOUT_SUCCESS).toJson();
        }

        /**
         *@api {GET} /api/app/log/logState  检查app登录状态
         * @apiGroup MemberLogin
         * @apiName checkState
         *  @apiDescription 检测是否登录，未登录则会被拦截，不能到达这里
         *  @apiSuccessExample {json} 返回样例:
         *  {
         *      "true"
         *  }
         */
        @RequestMapping(value = "/logState", method = RequestMethod.GET)
        public boolean checkState(){
                return true;
        }
}
